<template>
  <div class="order-detail">
    <PageHeader title="订单详情" />

    <!-- 订单状态卡片 -->
    <div class="status-card">
      <div class="status-icon">
        <van-icon :name="getStatusIcon()" :color="getStatusColor()" size="40" />
      </div>
      <div class="status-info">
        <div class="status-text">{{ order.status }}</div>
        <div class="status-desc">{{ getStatusDesc() }}</div>
      </div>
    </div>

    <!-- 收货信息 -->
    <div class="info-card">
      <div class="card-title">收货信息</div>
      <div class="info-item">
        <div class="label">收货人：</div>
        <div class="value">{{ order.receiver }}</div>
      </div>
      <div class="info-item">
        <div class="label">联系电话：</div>
        <div class="value">{{ order.phone }}</div>
      </div>
      <div class="info-item">
        <div class="label">收货地址：</div>
        <div class="value">{{ order.address }}</div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="info-card">
      <div class="card-title">订单信息</div>
      <div class="info-item">
        <div class="label">订单编号：</div>
        <div class="value">{{ order.orderNo }}</div>
      </div>
      <div class="info-item">
        <div class="label">创建时间：</div>
        <div class="value">{{ formatDate(order.createdAt) }}</div>
      </div>
      <div class="info-item">
        <div class="label">订单备注：</div>
        <div class="value">{{ order.remark || '无' }}</div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="info-card">
      <div class="card-title">商品信息</div>
      <div class="product-item" v-for="item in order.items" :key="item.id">
        <!-- <img :src="item.product.image" :alt="item.product.name" class="product-img" /> -->
        <div class="product-info">
          <div class="product-name">{{ item.productName }}</div>
          <div v-if="item.skuSpecs" class="product-specs">
            <span v-for="(value, key) in item.skuSpecs" :key="key">{{ key }}: {{ value }}</span>
          </div>
          <div class="product-price">{{ item.points }} 积分</div>
          <div class="product-quantity">x{{ item.quantity }}</div>
        </div>
      </div>
      <div class="order-total">
        <div>共{{ getTotalQuantity() }}件商品</div>
        <div>
          合计：
          <span class="price">{{ order.totalPoints }}</span>积分
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons" v-if="order.status !== '已完成' && order.status !== '已取消'">
      <van-button v-if="order.status === '待付款'" type="primary" block @click="payOrder">去支付</van-button>
      <van-button v-if="order.status === '待收货'" type="primary" block @click="confirmOrder">确认收货</van-button>
      <van-button
        v-if="order.status === '待付款' || order.status === '待发货'"
        type="default"
        block
        @click="cancelOrder"
      >取消订单</van-button>
    </div>

    <!-- 加载中 -->
    <div class="loading-mask" v-if="loading">
      <van-loading type="spinner" color="#1989fa" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showDialog, showSuccessToast, showFailToast } from 'vant'
import PageHeader from '@/components/PageHeader.vue'
import {
  getOrderDetail,
  confirmOrder as confirmOrderApi,
  cancelOrder as cancelOrderApi,
  payOrder as payOrderApi,
} from '@/api/order'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const order = ref<any>({
  items: [],
})

// 获取订单详情
const fetchOrderDetail = async () => {
  loading.value = true
  const id = route.params.id as string

  try {
    const res = await getOrderDetail(Number(id))
    if (res.code === 200 && res.data) {
      order.value = res.data
    } else {
      showFailToast('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    showFailToast('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 确认收货
const confirmOrder = async () => {
  try {
    await showDialog({
      title: '确认收货',
      message: '确认已收到商品吗？',
      showCancelButton: true,
    })

    const res = await confirmOrderApi(order.value.id)
    if (res.code === 200) {
      showSuccessToast('确认收货成功')
      fetchOrderDetail()
    }
  } catch (error) {
    console.error('确认收货失败:', error)
  }
}

// 取消订单
const cancelOrder = async () => {
  try {
    await showDialog({
      title: '取消订单',
      message: '确认要取消该订单吗？',
      showCancelButton: true,
    })

    const res = await cancelOrderApi(order.value.id)
    if (res.code === 200) {
      showSuccessToast('取消订单成功')
      fetchOrderDetail()
    }
  } catch (error) {
    console.error('取消订单失败:', error)
  }
}

// 支付订单
const payOrder = async () => {
  try {
    await showDialog({
      title: '确认支付',
      message: `确认支付该订单吗？将从您的积分中扣除 ${order.value.totalPoints} 积分`,
      showCancelButton: true,
    })

    const res = await payOrderApi(order.value.id)
    if (res.code === 200) {
      showSuccessToast('支付成功')
      fetchOrderDetail()
    } else {
      showDialog({
        title: '支付失败',
        message: res.message || '支付失败，请稍后再试',
      })
    }
  } catch (error) {
    console.error('支付订单失败:', error)
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    '0'
  )}-${String(date.getDate()).padStart(2, '0')} ${String(
    date.getHours()
  ).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态图标
const getStatusIcon = () => {
  const status = order.value.status
  switch (status) {
    case '待发货':
      return 'clock-o'
    case '待收货':
      return 'logistics'
    case '已完成':
      return 'checked'
    case '已取消':
      return 'close'
    default:
      return 'clock-o'
  }
}

// 获取状态颜色
const getStatusColor = () => {
  const status = order.value.status
  switch (status) {
    case '待发货':
      return '#1989fa'
    case '待收货':
      return '#ff976a'
    case '已完成':
      return '#07c160'
    case '已取消':
      return '#969799'
    default:
      return '#1989fa'
  }
}

// 获取状态描述
const getStatusDesc = () => {
  const status = order.value.status
  switch (status) {
    case '待发货':
      return '商家正在处理您的订单'
    case '待收货':
      return '商品已发出，请注意查收'
    case '已完成':
      return '订单已完成，感谢您的购买'
    case '已取消':
      return '订单已取消'
    default:
      return ''
  }
}

// 获取商品总数量
const getTotalQuantity = () => {
  return order.value.items.reduce(
    (total: number, item: any) => total + item.quantity,
    0
  )
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped lang="scss">
.order-detail {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 50px;
}

.status-card {
  background-color: $primary-color;
  padding: $padding-lg;
  display: flex;
  align-items: center;
  color: $white;

  .status-icon {
    margin-right: $padding-md;
  }

  .status-info {
    .status-text {
      font-size: $font-size-xl;
      font-weight: 500;
      margin-bottom: $padding-xs;
    }

    .status-desc {
      font-size: $font-size-sm;
      opacity: 0.9;
    }
  }
}

.info-card {
  background-color: $white;
  margin-top: $padding-xs;
  padding: $padding-md;

  .card-title {
    font-size: $font-size-md;
    font-weight: 500;
    margin-bottom: $padding-md;
    padding-bottom: $padding-xs;
    border-bottom: 1px solid #f5f5f5;
  }

  .info-item {
    display: flex;
    margin-bottom: $padding-sm;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: $text-color-light;
      min-width: 70px;
    }

    .value {
      flex: 1;
      color: $text-color;
    }
  }
}

.product-item {
  display: flex;
  padding: $padding-sm 0;
  border-bottom: 1px solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  .product-img {
    width: 70px;
    height: 70px;
    object-fit: cover;
    border-radius: $border-radius-sm;
    margin-right: $padding-md;
  }

  .product-info {
    flex: 1;
    position: relative;

    .product-name {
      font-size: $font-size-md;
      color: $text-color;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: $padding-xs;
    }

    .product-specs {
      font-size: $font-size-sm;
      color: $text-color-light;
      margin-bottom: $padding-xs;
    }

    .product-price {
      font-size: $font-size-md;
      color: $danger-color;
    }

    .product-quantity {
      position: absolute;
      right: 0;
      bottom: 0;
      font-size: $font-size-sm;
      color: $text-color-light;
    }
  }
}

.order-total {
  display: flex;
  justify-content: space-between;
  margin-top: $padding-md;
  padding-top: $padding-md;
  border-top: 1px solid #f5f5f5;

  .price {
    color: $danger-color;
    font-weight: 500;
  }
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: $padding-sm;
  background-color: $white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
</style> 